package com.ssy.lingxi.logistics.serviceimpl;

import cn.hutool.core.util.StrUtil;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.model.vo.PageVO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.logistics.api.dto.request.CommonIdRequest;
import com.ssy.lingxi.logistics.api.dto.request.CommonIdsRequest;
import com.ssy.lingxi.logistics.api.dto.response.ShipperAddressDetailResponse;
import com.ssy.lingxi.logistics.entity.ShipperAddress;
import com.ssy.lingxi.logistics.model.enums.CommonBooleanEnum;
import com.ssy.lingxi.logistics.model.request.ShipperAddressRequest;
import com.ssy.lingxi.logistics.model.request.StoreShipperAddressListRequest;
import com.ssy.lingxi.logistics.model.response.ShipperAddressListResponse;
import com.ssy.lingxi.logistics.model.response.ShipperAddressResponse;
import com.ssy.lingxi.logistics.model.response.StoreShipperAddressListResponse;
import com.ssy.lingxi.logistics.repository.ShipperAddressRepository;
import com.ssy.lingxi.logistics.service.IShipperAddressService;
import com.ssy.lingxi.logistics.util.LogisticsAddressUtil;
import com.ssy.lingxi.product.api.feign.ICommodityFeign;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 发货地址服务实现类
 * @author yzc
 * @version 2.0.0
 * @date 2020/7/13
 */
@Service
public class ShipperAddressServiceImpl implements IShipperAddressService {

    @Resource
    private ShipperAddressRepository shipperAddressRepository;
    @Resource
    private ICommodityFeign commodityFeign;


    @Override
    public Wrapper<PageData<ShipperAddressListResponse>> pageShipperAddress(PageVO request, UserLoginCacheDTO loginUser) {
        Pageable page = PageRequest.of(request.getCurrent() - 1, request.getPageSize(), Sort.by("id").ascending());
        Page<ShipperAddress> pageList = shipperAddressRepository.findAllByMemberIdAndRoleId(loginUser.getMemberId(), loginUser.getMemberRoleId(), page);

        // 组装数据
        List<ShipperAddressListResponse> resultList = pageList.stream().map(e -> {
            ShipperAddressListResponse shipperAddressListResponse = new ShipperAddressListResponse();
            shipperAddressListResponse.setId(e.getId());
            shipperAddressListResponse.setShipperName(e.getShipperName());
            shipperAddressListResponse.setPostalCode(e.getPostalCode());
            shipperAddressListResponse.setPhone(e.getPhone());
            shipperAddressListResponse.setTel(e.getTel());
            shipperAddressListResponse.setIsDefault(e.getIsDefault());
            shipperAddressListResponse.setIsStore(e.getIsStore());
            shipperAddressListResponse.setStoreName(StrUtil.isEmpty(e.getStoreName()) ? "" : e.getStoreName());

            // 拼接完整的地址
            String fullAddress = LogisticsAddressUtil.contractFullAddress(e.getProvinceName(), e.getCityName(), e.getDistrictName(), e.getStreetName(), e.getAddress());
            shipperAddressListResponse.setFullAddress(fullAddress);
            return shipperAddressListResponse;
        }).collect(Collectors.toList());

        return Wrapper.success(new PageData<>(pageList.getTotalElements(), resultList));
    }

    @Override
    public Wrapper<ShipperAddressResponse> getShipperAddress(Long id) {
        // 无参返回空
        if (Objects.isNull(id)) {
            return Wrapper.success();
        }
        ShipperAddress shipperAddress = shipperAddressRepository.findById(id).orElse(null);
        if (Objects.isNull(shipperAddress)) {
            return Wrapper.fail(ResponseCode.LS_RECORDS_DON_T_EXIST);
        }

        ShipperAddressResponse shipperAddressResponse = new ShipperAddressResponse();
        shipperAddressResponse.setId(shipperAddress.getId());
        shipperAddressResponse.setShipperName(shipperAddress.getShipperName());
        shipperAddressResponse.setProvinceCode(shipperAddress.getProvinceCode());
        shipperAddressResponse.setProvinceName(shipperAddress.getProvinceName());
        shipperAddressResponse.setCityCode(shipperAddress.getCityCode());
        shipperAddressResponse.setCityName(shipperAddress.getCityName());
        shipperAddressResponse.setDistrictCode(shipperAddress.getDistrictCode());
        shipperAddressResponse.setDistrictName(shipperAddress.getDistrictName());
        shipperAddressResponse.setStreetCode(shipperAddress.getStreetCode());
        shipperAddressResponse.setStreetName(shipperAddress.getStreetName());
        shipperAddressResponse.setAddress(shipperAddress.getAddress());
        shipperAddressResponse.setPostalCode(shipperAddress.getPostalCode());
        shipperAddressResponse.setAreaCode(shipperAddress.getAreaCode());
        shipperAddressResponse.setPhone(shipperAddress.getPhone());
        shipperAddressResponse.setTel(shipperAddress.getTel());
        shipperAddressResponse.setIsDefault(shipperAddress.getIsDefault());

        return Wrapper.success(shipperAddressResponse);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Wrapper<ShipperAddressResponse> addShipperAddress(ShipperAddressRequest request, UserLoginCacheDTO loginUser) {
        // 手机校验
        if (!LogisticsAddressUtil.validatePhone(request.getPhone())) {
            return Wrapper.fail(ResponseCode.LS_DATA_PHONE_VALIDATE);
        }

        // 电话校验
//        if (!LogisticsAddressUtil.validateTel(request.getTel())) {
//            return Wrapper.fail(ResponseCode.LS_DATA_TEL_VALIDATE);
//        }

        ShipperAddress shipperAddress = new ShipperAddress();

        updateAllStateNotDefault(request.getIsDefault(), loginUser.getMemberId(), loginUser.getMemberRoleId());

        shipperAddress.setShipperName(request.getShipperName());
        shipperAddress.setProvinceCode(request.getProvinceCode());
        shipperAddress.setProvinceName(request.getProvinceName());
        shipperAddress.setCityCode(request.getCityCode());
        shipperAddress.setCityName(request.getCityName());
        shipperAddress.setDistrictCode(request.getDistrictCode());
        shipperAddress.setDistrictName(request.getDistrictName());
        shipperAddress.setStreetCode(request.getStreetCode());
        shipperAddress.setStreetName(request.getStreetName());
        shipperAddress.setAddress(request.getAddress());
        shipperAddress.setPostalCode(request.getPostalCode());
        shipperAddress.setAreaCode(request.getAreaCode());
        shipperAddress.setPhone(request.getPhone());
        shipperAddress.setTel(request.getTel());
        shipperAddress.setIsDefault(request.getIsDefault());
        shipperAddress.setMemberId(loginUser.getMemberId());
        shipperAddress.setRoleId(loginUser.getMemberRoleId());
        shipperAddress.setCreateTime(System.currentTimeMillis());
        //新增物流地址没有门店地址信息，设为默认值
        shipperAddress.setStoreId(0L);
        shipperAddress.setStoreName("");
        shipperAddress.setIsStore(CommonBooleanEnum.NO.getCode());
        shipperAddressRepository.saveAndFlush(shipperAddress);

        ShipperAddressResponse shipperAddressResponse = new ShipperAddressResponse();
        shipperAddressResponse.setId(shipperAddress.getId());
        shipperAddressResponse.setShipperName(shipperAddress.getShipperName());
        shipperAddressResponse.setProvinceCode(shipperAddress.getProvinceCode());
        shipperAddressResponse.setProvinceName(shipperAddress.getProvinceName());
        shipperAddressResponse.setCityCode(shipperAddress.getCityCode());
        shipperAddressResponse.setCityName(shipperAddress.getCityName());
        shipperAddressResponse.setDistrictCode(shipperAddress.getDistrictCode());
        shipperAddressResponse.setDistrictName(shipperAddress.getDistrictName());
        shipperAddressResponse.setStreetCode(shipperAddress.getStreetCode());
        shipperAddressResponse.setStreetName(shipperAddress.getStreetName());
        shipperAddressResponse.setAddress(shipperAddress.getAddress());
        shipperAddressResponse.setPostalCode(shipperAddress.getPostalCode());
        shipperAddressResponse.setAreaCode(shipperAddress.getAreaCode());
        shipperAddressResponse.setPhone(shipperAddress.getPhone());
        shipperAddressResponse.setTel(shipperAddress.getTel());
        shipperAddressResponse.setIsDefault(shipperAddress.getIsDefault());

        return Wrapper.success(shipperAddressResponse);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Wrapper<Void> updateShipperAddress(ShipperAddressRequest request, UserLoginCacheDTO loginUser) {
        // 手机校验
        // 手机校验
        if (!LogisticsAddressUtil.validatePhone(request.getPhone())) {
            return Wrapper.fail(ResponseCode.LS_DATA_PHONE_VALIDATE);
        }

        // 电话校验
//        if (!LogisticsAddressUtil.validateTel(request.getTel())) {
//            return Wrapper.fail(ResponseCode.LS_DATA_TEL_VALIDATE);
//        }

        ShipperAddress shipperAddress = shipperAddressRepository.findByIdAndMemberIdAndRoleId(request.getId(), loginUser.getMemberId(), loginUser.getMemberRoleId());
        if (Objects.isNull(shipperAddress)) {
            return Wrapper.fail(ResponseCode.LS_RECORDS_DON_T_EXIST);
        }

        updateAllStateNotDefault(request.getIsDefault(), loginUser.getMemberId(), loginUser.getMemberRoleId());

        shipperAddress.setShipperName(request.getShipperName());
        shipperAddress.setProvinceCode(request.getProvinceCode());
        shipperAddress.setProvinceName(request.getProvinceName());
        shipperAddress.setCityCode(request.getCityCode());
        shipperAddress.setCityName(request.getCityName());
        shipperAddress.setDistrictCode(request.getDistrictCode());
        shipperAddress.setDistrictName(request.getDistrictName());
        shipperAddress.setStreetCode(request.getStreetCode());
        shipperAddress.setStreetName(request.getStreetName());
        shipperAddress.setAddress(request.getAddress());
        shipperAddress.setPostalCode(request.getPostalCode());
        shipperAddress.setAreaCode(request.getAreaCode());
        shipperAddress.setPhone(request.getPhone());
        shipperAddress.setTel(request.getTel());
        shipperAddress.setIsDefault(request.getIsDefault());

        shipperAddressRepository.saveAndFlush(shipperAddress);

        return Wrapper.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Wrapper<Void> deleteShipperAddress(CommonIdRequest request, UserLoginCacheDTO loginUser) {
        ShipperAddress shipperAddress = shipperAddressRepository.findByIdAndMemberIdAndRoleId(request.getId(), loginUser.getMemberId(), loginUser.getMemberRoleId());
        if (Objects.isNull(shipperAddress)) {
            return Wrapper.fail(ResponseCode.LS_RECORDS_DON_T_EXIST);
        }

        // 商品关联,不能删除
        Wrapper<Boolean> commodityUseSendAddress = commodityFeign.getCommodityUseSendAddress(request.getId());
        if (ResponseCode.SUCCESS.getCode() != commodityUseSendAddress.getCode()) {
            return Wrapper.fail(ResponseCode.SERVICE_PRODUCT_ERROR);
        }
        if (commodityUseSendAddress.getData()) {
            return Wrapper.fail(ResponseCode.LS_DATA_RELATION_PRODUCT_DEL);
        }

        shipperAddressRepository.deleteById(shipperAddress.getId());

        return Wrapper.success();
    }

    /**
     * 修改所有记录为非默认
     * @param isDefault
     */
    private void updateAllStateNotDefault(Integer isDefault, Long memberId, Long roleId) {
        if (CommonBooleanEnum.YES.getCode().equals(isDefault)) {
            List<ShipperAddress> isDefaultList = shipperAddressRepository.findAllByIsDefaultAndMemberIdAndRoleId(CommonBooleanEnum.YES.getCode(), memberId, roleId);
            List<ShipperAddress> updateList = isDefaultList.stream().peek(e -> e.setIsDefault(CommonBooleanEnum.NO.getCode())).collect(Collectors.toList());
            shipperAddressRepository.saveAll(updateList);
        }
    }

    @Override
    public Wrapper<ShipperAddressDetailResponse> getShipperAddressDetail(Long id) {
        ShipperAddress shipperAddress = shipperAddressRepository.findById(id).orElse(null);
        if (Objects.isNull(shipperAddress)) {
            return Wrapper.fail(ResponseCode.LS_RECORDS_DON_T_EXIST);
        }

        ShipperAddressDetailResponse response = new ShipperAddressDetailResponse();
        // 拼接完整的地址
        String fullAddress = LogisticsAddressUtil.contractFullAddress(shipperAddress.getProvinceName(), shipperAddress.getCityName(), shipperAddress.getDistrictName(), shipperAddress.getStreetName(), shipperAddress.getAddress());
        response.setId(shipperAddress.getId());
        response.setFullAddress(fullAddress);
        response.setShipperName(shipperAddress.getShipperName());
        response.setPhone(shipperAddress.getPhone());

        return Wrapper.success(response);
    }

    @Override
    public Wrapper<List<ShipperAddressDetailResponse>> listShipperAddress(CommonIdsRequest idsRequest) {
        List<ShipperAddress> shipperAddressList = shipperAddressRepository.findAllById(idsRequest.getIds());
        if (CollectionUtils.isEmpty(shipperAddressList)) {
            return Wrapper.fail(ResponseCode.LS_RECORDS_DON_T_EXIST);
        }

        List<ShipperAddressDetailResponse> responseList = shipperAddressList.stream().map(shipperAddress -> {
            ShipperAddressDetailResponse response = new ShipperAddressDetailResponse();
            // 拼接完整的地址
            String fullAddress = LogisticsAddressUtil.contractFullAddress(shipperAddress.getProvinceName(), shipperAddress.getCityName(), shipperAddress.getDistrictName(), shipperAddress.getStreetName(), shipperAddress.getAddress());

            response.setId(shipperAddress.getId());
            response.setProvinceCode(shipperAddress.getProvinceCode());
            response.setProvinceName(shipperAddress.getProvinceName());
            response.setCityCode(shipperAddress.getCityCode());
            response.setCityName(shipperAddress.getCityName());
            response.setDistrictCode(shipperAddress.getDistrictCode());
            response.setDistrictName(shipperAddress.getDistrictName());
            response.setStreetCode(shipperAddress.getStreetCode());
            response.setStreetName(shipperAddress.getStreetName());
            response.setAddress(shipperAddress.getAddress());
            response.setShipperName(shipperAddress.getShipperName());
            response.setPhone(shipperAddress.getPhone());
            response.setFullAddress(fullAddress);
            return response;
        }).collect(Collectors.toList());

        return Wrapper.success(responseList);
    }

    /**
     * 门店发货地址列表
     * @param request 接口参数
     * @return 返回结果
     */
    @Override
    public Wrapper<List<StoreShipperAddressListResponse>> storeShipperAddressList(StoreShipperAddressListRequest request) {
        List<ShipperAddress> storeAddressList = shipperAddressRepository.findAllByMemberIdAndRoleIdAndStoreStatus(request.getVendorMemberId(), request.getVendorRoleId(), CommonBooleanEnum.YES.getCode(), Sort.by("id").descending());

        List<StoreShipperAddressListResponse> resultList = storeAddressList.stream().map(e -> {
            StoreShipperAddressListResponse addressListResponse = new StoreShipperAddressListResponse();
            addressListResponse.setId(e.getId());
            addressListResponse.setStoreId(e.getStoreId());
            addressListResponse.setShipperName(e.getShipperName());
            addressListResponse.setProvinceCode(e.getProvinceCode());
            addressListResponse.setProvinceName(e.getProvinceName());
            addressListResponse.setCityCode(e.getCityCode());
            addressListResponse.setCityName(e.getCityName());
            addressListResponse.setDistrictCode(e.getDistrictCode());
            addressListResponse.setDistrictName(e.getDistrictName());
            addressListResponse.setStreetCode(e.getStreetCode());
            addressListResponse.setStreetName(e.getStreetName());
            addressListResponse.setAddress(e.getAddress());
            addressListResponse.setPostalCode(e.getPostalCode());
            addressListResponse.setPhone(e.getPhone());
            addressListResponse.setTel(e.getTel());
            addressListResponse.setIsDefault(e.getIsDefault());
            addressListResponse.setStoreName(StrUtil.isEmpty(e.getStoreName()) ? "" : e.getStoreName());

            // 拼接完整的地址
            String fullAddress = LogisticsAddressUtil.contractFullAddress(e.getProvinceName(), e.getCityName(), e.getDistrictName(), e.getStreetName(), e.getAddress());
            addressListResponse.setFullAddress(fullAddress);
            return addressListResponse;
        }).collect(Collectors.toList());

        return Wrapper.success(resultList);
    }
}